package com.guli.educenter.controller;

import com.google.gson.Gson;
import com.guli.commonutils.JwtUtils;
import com.guli.educenter.entity.UcenterMember;
import com.guli.educenter.service.UcenterMemberService;
import com.guli.educenter.utils.ConstantWxUtils;
import com.guli.educenter.utils.HttpClientUtils;
import com.guli.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "微信登录")
@Controller
@RequestMapping("/api/ucenter/wx")
@CrossOrigin
public class WxApiController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    @ApiOperation(value = "生成vx扫描二维码")
    @GetMapping("login")
    public String getWxCode() {
        // 微信开放平台授权baseUrl  %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url 进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;

        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguli"
        );
        //重定向到请求的微信地址
        return "redirect:" + url;
    }

    @ApiOperation(value = "获取扫描人的信息")
    @GetMapping("callback")
    public String callback(String code, String state) {
        try {
            //1.获取code值，类似于手机验证码

            //2.用code取请求微信的固定地址，得到access_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接参数
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code
            );
            //请求地址 使用httpClient发送请求
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //从accessTokenInfo中取出access_token和 openid
            //使用json转换工具---把从accessTokenInfo转换为map ，根据key取出值
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            String openid = (String) mapAccessToken.get("openid");

            //把扫码人的信息添加到数据库中（扫描登录并注册）
            //判断是否存在信息
            UcenterMember ucenterMember = ucenterMemberService.getOpenIdMember(openid);
            if (ucenterMember == null) { //不存在数据，添加
                //3 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        access_token,
                        openid
                );
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取userInfo中用户信息
                HashMap userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nikename = (String) userInfoMap.get("nikename"); //昵称
                String headimgurl = (String) userInfoMap.get("headimgurl"); //头像

                UcenterMember member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nikename);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
            }
            //使用jwt根据member对象生成token，通过路径进行传递，解决cookie不能跨域
            String jwtToken = JwtUtils.getJwtToken(ucenterMember.getId(), ucenterMember.getNickname());

            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new GuliException(20001, "登录失败");
        }
    }
}